<template>
  <!-- <v-card elevation="2"> -->
  <div class="card-padding">
    <div
      class="highlight-container highlight-container--bottom-labels"
      @click="open"
      @touchend="open"
    >
      <entity-item
        class="oto"
        v-for="(chunk, i) in chunks"
        :key="i"
        :content="chunk.text"
        :newline="chunk.newline"
        :label="chunk.name"
        :color="chunk.color"
        :labels="labels"
        @remove="deleteAnnotation(chunk.id)"
        @update="updateEntity($event.id, chunk.id)"
      />
      <v-menu
        class="tree"
        v-model="showMenu"
        :position-x="x"
        :position-y="y"
        absolute
        offset-y
      >
        <v-list dense min-width="150" max-height="400" class="overflow-y-auto">
          <v-list-item
            ><v-list-item-icon>
              <v-icon color="red" v-text="itemw.icon"></v-icon>
            </v-list-item-icon>
            <v-list-item-content>
              <v-list-item-title
                class="itemT"
                v-text="itemw.text"
              ></v-list-item-title> </v-list-item-content
          ></v-list-item>
        </v-list>
        <v-treeview
          item-disabled
          dense
          class="tree"
          activatable
          hoverable
          :items="iData"
          rounded
          @update:active="handleClick"
        ></v-treeview>
      </v-menu>
    </div>
    <!-- <v-chip outlined class="ma-2 pose" color="red" text-color="red">
      <span></span>
      <span v-for="chunk in recommend" :key="chunk">
        {{ `${chunk}&nbsp;&nbsp;&nbsp;${space}` }}
      </span>
      <v-icon right> mdi-star </v-icon>
    </v-chip> -->
    <div class="btnGroup">
      <v-btn
        class="btn btn-group"
        v-for="chunk in recommend"
        :key="chunk"
        outlined
        color="#1976d2"
        @click="chooseBtn(chunk)"
      >
        {{ `${chunk}` }}
      </v-btn>
    </div>
  </div>
  <!-- </v-card> -->
</template>

<script>
import { mapMutations, mapActions, mapState } from 'vuex'
import EntityItem from '~/components/molecules/EntityItem'
export default {
  components: {
    EntityItem
  },
  props: {
    // 判断初始化是否选中白色按钮的状态
    writeStatus: {
      type: Boolean
    },
    // 判断初始化是否选中红色按钮的状态
    status: {
      type: Boolean,
      // default: true,
      required: true
    },
    // 判断传过来的是不是 flag true  和 false
    item: {
      type: Object
    },
    documentId: {
      type: Object
    },
    radio: {
      type: Number
    },
    text: {
      type: String,
      default: '',
      required: true
    },
    labels: {
      type: Array,
      default: () => []
    },
    entities: {
      type: Array,
      default: () => [],
      required: true
    },
    deleteAnnotation: {
      type: Function,
      default: () => [],
      required: true
    },
    updateEntity: {
      type: Function,
      default: () => [],
      required: true
    },
    addEntity: {
      type: Function,
      default: () => [],
      required: true
    },
    count: {
      type: Number
    },
    treeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      space: '  ',
      itemw: {
        icon: 'mdi-cancel',
        text: '请选择子标签！'
      },
      recommend: [],
      showMenu: false,
      x: 0,
      y: 0,
      start: 0,
      end: 0,
      iData: [],
      itemId: null
    }
  },
  computed: {
    ...mapState('user', ['flag']),
    ...mapState('documents', ['isUser']),
    sortedEntities() {
      return this.entities
        .slice()
        .sort((a, b) => a.start_offset - b.start_offset)
    },

    chunks() {
      let chunks = []
      const entities = this.sortedEntities
      let startOffset = 0
      for (const entity of entities) {
        // add non-entities to chunks.
        chunks = chunks.concat(
          this.makeChunks(this.text.slice(startOffset, entity.start_offset))
        )
        startOffset = entity.end_offset
        // add entities to chunks.
        const label = this.labelObject[entity.label]
        chunks.push({
          id: entity.id,
          label: label === undefined ? '' : label.text,
          name: label === undefined ? '' : label.label_name,
          color: label === undefined ? '' : label.background_color,
          text: this.text.slice(entity.start_offset, entity.end_offset)
        })
      }
      // add the rest of text.
      chunks = chunks.concat(
        this.makeChunks(this.text.slice(startOffset, this.text.length))
      )
      this.$emit('deleteChunks', chunks)
      if (chunks.length > 3 && this.radio !== 0) {
        // localStorage.setItem('topLevel', '只点击了上面')
      } else {
        localStorage.removeItem('topLevel')
      }
      if (chunks.length <= 3) {
        // 2021.8.26测试 bug 获取localstorage
        // localStorage.removeItem('alreadyTopLevel')
        localStorage.removeItem('TopLevel')
        localStorage.removeItem('topLevel')
      }
      console.log(this.text)
      console.log(chunks)
      return chunks
    },

    labelObject() {
      const obj = {}
      for (const label of this.labels) {
        obj[label.id] = label
      }
      return obj
    }
  },
  methods: {
    ...mapActions('user', ['getFlag']),
    ...mapMutations('labels', ['setInitialRadioStatus']),
    ...mapActions('labels', ['getInitialRadioStatus']),
    chooseBtn(item) {
      this.$emit('advancedRetrieval', item)
    },
    async handleClick(item) {
      if (item[0] === null) {
        this.showMenu = true
      }
      this.iData.forEach((e) => {
        if (e.children) {
        }
      })
      if (item.length !== 0) {
        this.itemId = item
      }
      if (item.length === 0) {
        item = this.itemId
      }
      // 2021.8.15  判断 翻页
      if (sessionStorage.getItem('radioStatus') && this.chunks.length >= 1) {
        console.log(this.chunks)
        // 2021.8.15
        localStorage.setItem('topLevela', '先点radio保存成功')
      }
      if (this.validateSpan()) {
        if (item[0] !== null) {
          // 增加 标注的 2021.8.16 防止导出 offset 报错
          if (this.end > this.text.length) {
            this.end = this.text.length
          }
          await this.addEntity(this.start, this.end, item[0])
          // 增加 意图的
          // await DocumentService.getDocumentListLabels(
          //   this.radio,
          //   this.documentId.id
          // )
          this.showMenu = false
          this.start = 0
          this.end = 0
          // 返回状态
          this.$emit('state', [true, this.chunks.length])
        }
      }
    },
    makeChunks(text) {
      const chunks = []
      const snippets = text.split('\n')
      for (const snippet of snippets.slice(0, -1)) {
        chunks.push({
          label: null,
          color: null,
          text: snippet + '\n',
          newline: false
        })
        chunks.push({
          label: null,
          color: null,
          text: '',
          newline: true
        })
      }
      chunks.push({
        label: null,
        color: null,
        text: snippets.slice(-1)[0],
        newline: false
      })
      return chunks
    },
    show(e) {
      e.preventDefault()
      this.showMenu = false
      this.x = e.clientX || e.changedTouches[0].clientX
      this.y = e.clientY || e.changedTouches[0].clientY
      this.$nextTick(() => {
        this.showMenu = true
      })
    },
    setSpanInfo() {
      let selection
      // Modern browsers.
      if (window.getSelection) {
        selection = window.getSelection()
      } else if (document.selection) {
        selection = document.selection
      }
      // If nothing is selected.
      if (selection.rangeCount <= 0) {
        return
      }
      const range = selection.getRangeAt(0)
      const preSelectionRange = range.cloneRange()
      preSelectionRange.selectNodeContents(this.$el)
      preSelectionRange.setEnd(range.startContainer, range.startOffset)
      this.start = [...preSelectionRange.toString()].length
      this.end = this.start + [...range.toString()].length
      console.log(this.start)
      console.log(this.end)
    },
    validateSpan() {
      if (
        typeof this.start === 'undefined' ||
        typeof this.end === 'undefined'
      ) {
        return false
      }
      if (this.start === this.end) {
        return false
      }
      for (const entity of this.entities) {
        if (
          entity.start_offset <= this.start &&
          this.start < entity.end_offset
        ) {
          return false
        }
        if (entity.start_offset < this.end && this.end <= entity.end_offset) {
          return false
        }
        if (this.start < entity.start_offset && entity.end_offset < this.end) {
          return false
        }
      }
      return true
    },
    open(e) {
      this.setSpanInfo()
      if (this.validateSpan()) {
        if (sessionStorage.getItem('radioStatus') !== 'false') {
          this.show(e)
        }
        if (
          sessionStorage.getItem('radioStatus') !== 'false' &&
          this.chunks.length >= 3
        ) {
          this.show(e)
          // localStorage.setItem('topLevel', '滑动保存成功')
        }
      }
    },
    async watchRecommendButton() {
      await this.getFlag(this.documentId.id)
      console.log(this.flag.slot_flg)
      sessionStorage.setItem('radioStatus', this.flag.slot_flg)
      sessionStorage.removeItem('radioStatus')
      this.recommend = this.flag.docAnn
      // 优化修改bug
      if (this.chunks.length <= 3) {
        // 2021.9.1 修改预防不能分页bug
        // localStorage.removeItem('alreadyTopLevel')
        localStorage.removeItem('TopLevel')
      }
    }
  },
  updated() {
    if (this.isUser.user) {
    } else {
    }
    if (
      this.chunks.length <= 3 &&
      sessionStorage.getItem('radioStatus') === 'true'
    ) {
      localStorage.removeItem('alreadyTopLevel')
      localStorage.removeItem('TopLevel')
    }
    if (this.chunks.length <= 3) {
      // localStorage.removeItem('alreadyTopLevel')
      localStorage.removeItem('TopLevel')
    }
    // 判断按钮 白色红色 点击状态
    // if (this.item.slot_flg === false) {
    //   this.showMenu = false
    // }
    // 默认红色
    // if (this.status === false) {
    //   this.showMenu = false
    // }
    // if (this.writeStatus === true) {
    //   this.showMenu = true
    // }
  },
  created() {
    // // 2021.9.1 优化接口数量
    // await this.getFlag(this.documentId.id)
    // sessionStorage.setItem('radioStatus', this.flag.slot_flg)
    // this.recommend = this.flag.docAnn
    // // 优化修改bug
    // if (this.chunks.length <= 3) {
    //   // 2021.9.1 修改预防不能分页bug
    //   // localStorage.removeItem('alreadyTopLevel')
    //   localStorage.removeItem('TopLevel')
    // }
    // const data = await LabelService.getLabels()
    const treeData = this.treeData
    // const treeData = []
    treeData.forEach((item) => {
      item.id = null
    })
    this.iData = treeData
  },
  watch: {
    documentId: {
      handler(newValue) {
        this.watchRecommendButton()
      },
      immediate: true
    },
    chunks: {
      handler(ne, ol) {},
      immediate: true
    },
    count: {
      handler(ne, ol) {
        if (ne) {
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.highlight-container.highlight-container--bottom-labels {
  align-items: flex-start;
}
.highlight-container {
  /* background: red; */
  line-height: 42px !important;
  display: flex;
  flex-wrap: wrap;
  white-space: pre-wrap;
  cursor: default;
}
.highlight-container.highlight-container--bottom-labels .highlight.bottom {
  margin-top: 6px;
}
.tree {
  background: #fff;
}
.itemT {
  color: red;
}
.card-padding {
  padding: 10px;
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
  justify-content: flex-end;
}
.oto {
  font-weight: bold;
}
.ma-2 {
}
.pose {
  font-weight: bold;
  font-size: 18px;
}
.btn-group {
  margin: 10px;
  font-weight: bold;
}
</style>
